package com.bruce.practice.thread.demo;

import javax.annotation.PostConstruct;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static java.util.concurrent.TimeUnit.SECONDS;

/**
 * @author luotuan
 * @Description
 * @create 2020-05-19 16:16
 **/
public class CancelTest {
    private static final ExecutorService EXECUTOR_SERVICE = Executors.newFixedThreadPool(10);
    public static void main(String[] args) {
        PrimeGenetor genetor = new PrimeGenetor();
        new Thread(genetor).start();
        try {
            SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            genetor.cancel();
        }
        genetor.get();
    }
}
class PrimeGenetor implements Runnable{
    private static final List<BigInteger> primes = new ArrayList<>();
    private volatile boolean cancelled;
    @Override
    public void run() {
        BigInteger b = BigInteger.ONE;
        while (!cancelled){
            b = b.nextProbablePrime();
            synchronized (this){
                primes.add(b);
            }
        }
    }
    public void cancel(){
        cancelled = true;
    }
    public synchronized List<BigInteger> get(){
        return new ArrayList<>(primes);
    }
}
